package com.endlessblue.visa.util;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;


/**
 * 短信工具类
 * 阿里大鱼
 * 
 * @author sonta
 *
 */
public class ALISMSUtil {
	private static final Logger logger = LoggerFactory.getLogger(ALISMSUtil.class);
	private static TaobaoClient client;
	static {
		loadConfiguration();
	}
	private static final void loadConfiguration() {
		String url = PropertyUtil.getValue("business", "ALI_SMS_URL");
		String key = PropertyUtil.getValue("business", "ALI_SMS_APPKEY");
		String secret = PropertyUtil.getValue("business", "ALI_SMS_APPSECRET");
		if (StringUtil.isEmpty(url) || StringUtil.isEmpty(key) || StringUtil.isEmpty(secret)) {
			logger.error("load alidayu sms configuration failed");
			throw new RuntimeException("load alidayu sms configuration failed");
		}
		client = new DefaultTaobaoClient(url, key, secret);
	}
	
	/**
	 * 发送短信
	 * 通过阿里大鱼发送
	 * @param telNo 手机号
	 * @param param 模板参数
	 * @param extend 回传参数
	 * @param signName 签名模板
	 * @param templateCode 短信参数模板ID
	 * @return
	 */
	public static boolean sendSMS(String telNo, Map<String, String> param,
			String extend, String signName, String templateCode) {
		if (client == null) {
			loadConfiguration();
		}
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend(extend);
		req.setSmsType("normal");
		req.setSmsFreeSignName(signName);
		req.setSmsParamString(JsonUtil.toJson(param));
		req.setRecNum(telNo);
		req.setSmsTemplateCode(templateCode);
		AlibabaAliqinFcSmsNumSendResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			logger.error("send alidayu sms error", e);
			return false;
		}
		String res = rsp.getBody();
		Map<String, Object> retMap = JsonUtil.jsonToMap(res);
		logger.info("result - {}", retMap);
		@SuppressWarnings("unchecked")
		Map<String, Object> secMap = (Map<String, Object>) retMap.get("alibaba_aliqin_fc_sms_num_send_response");
		if (secMap == null) {
			return false;
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> reqRet = (Map<String, Object>) secMap.get("result");
		if (reqRet == null) {
			return false;
		}
		return "0".equals(reqRet.get("err_code"));
	}
	
	public static void main(String[] args) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("days", "5");
		ALISMSUtil.sendSMS("15673237766", param, "123456", "签证APP", "SMS_26065085");
	}
	
}
